import './index.scss';
import { Swiper, SwiperItem, Picker } from '@tarojs/components';
import { useState, useEffect, setWifiList } from '@tarojs/taro';
import { purchaseGood } from '../../services/goods';
import { fullImgUrl, timeFormat } from '../../utils/utils';
import fishImg from './img/detail-fish.png';
function Sku(props) {
  let navigationBarHeight = Taro.getStorageSync('navigationBarHeight');
  let findCardType = null;
  const { goodsAttr = [], goodsSku = [], goodsImage = [], exchangeData = null, code = '', goodsType = 0, electronicCardId } = { ...props };

  const [allSkuArr, setAllSkuArr] = useState(() => {
    if (!exchangeData) {
      let temp = goodsSku.map(sku => {
        let key = '';
        for (let i = 0; i < sku.has_goods_sku_attr_relation.length; i++) {
          key += sku.has_goods_sku_attr_relation[i].goods_sku_attr_name + ';';
        }
        return {
          value: key,
          sku_id: sku.sku_id,
          storage: sku.store_num,
          price: sku.price,
          cover: fullImgUrl(sku.cover)
        };
      })
      return temp;
    } else {
      //  card goods
      const { card, goods } = exchangeData

      // 兑换卡的类型
      findCardType = card.has_attr[0].has_goods_sku_attr.find(item => {
        return item.goods_sku_attr_id === card.select_attr[0]
      })

      // 过滤掉未使用的属性
      exchangeData.goods.has_attr.forEach(item => {
        let filterAttr = []
        item.has_goods_sku_attr.forEach(skuAttr => {
          let temp = exchangeData.goods.select_attr.find(seletedId => {
            return skuAttr.goods_sku_attr_id === seletedId
          })
          if (temp) {
            filterAttr.push(skuAttr)
          }
        })
        item.has_goods_sku_attr = filterAttr
      })

      let temp = goods.has_sku.map(sku => {
        let key = '';
        for (let i = 0; i < sku.has_goods_sku_attr_relation.length; i++) {
          key += sku.has_goods_sku_attr_relation[i].goods_sku_attr_name + ';';
        }
        return {
          value: key,
          sku_id: sku.sku_id,
          storage: sku.store_num,
          price: sku.price,
          cover: fullImgUrl(sku.cover)
        };
      })

      return temp;
    }
  });
  const [startDeliveryTime, setStartDeliveryTime] = useState(() => {
    let date = new Date();
    date.setDate(date.getDate() + 1);
    // 下午三点半以后，后天再发货
    if (date.getHours() > 15 || (date.getHours() === 15 && date.getMinutes() >= 30)) {
      date.setDate(date.getDate() + 1);
    }
    return timeFormat(parseInt(date.getTime() / 1000, 10), 'yyyy-MM-dd');
  });
  const [deliveryTime, setDeliveryTime] = useState(() => {
    let date = new Date();
    date.setDate(date.getDate() + 1);
    // 下午三点半以后，后天再发货
    if (date.getHours() > 15 || (date.getHours() === 15 && date.getMinutes() >= 30)) {
      date.setDate(date.getDate() + 1);
    }
    return timeFormat(parseInt(date.getTime() / 1000, 10), 'yyyy年MM月dd日');
  });
  const [purcharseNum, setPurcharseNum] = useState(1);
  const [checkedSku, setCheckedSku] = useState({});
  const [selectedAttr, setSelectedAttr] = useState(() => {
    if (!exchangeData) {
      let temp = {};
      goodsAttr.forEach(item => {
        let attr = item.has_goods_sku_attr[0];
        temp[attr.goods_attr_id] = {
          key: attr.goods_sku_attr_id,
          value: attr.attr_name,
        };
      });
      return temp;
    } else {
      let temp = {};
      exchangeData.goods.has_attr.forEach(item => {
        let attr = item.has_goods_sku_attr[0];
        temp[attr.goods_attr_id] = {
          key: attr.goods_sku_attr_id,
          value: attr.attr_name,
        };
      });
      return temp;
    }
  });


  useEffect(() => {
    checkStorage(selectedAttr)
  }, [])

  function checkStorage(sku) {
    if (Object.getOwnPropertyNames(sku).length === (exchangeData ? exchangeData.goods.has_attr.length : goodsAttr.length)) {
      let value = '';
      Object.keys(sku).forEach(item => {
        value += sku[item].value + ';';
      })
      let tempSku = allSkuArr.find(item => {
        return item.value === value
      })
      if (tempSku) {
        if (tempSku.storage <= 0) {
          console.log('库存为0');
          Taro.showToast({
            title: '该类型商品售罄了，正在补货中!',
            icon: 'none'
          });
        } else {
          console.log('找到了 库存为', tempSku.storage);
          console.log(tempSku.cover, 'tempSku')
          setCheckedSku({
            storage: tempSku.storage,
            skuId: tempSku.sku_id,
            price: tempSku.price,
            cover: tempSku.cover
          })
          setSelectedAttr(sku);
        }
      } else {
        if (exchangeData) {
          Taro.showToast({
            title: '兑换卡不能兑换该类型商品!',
            icon: 'none'
          });
        }
      }
    }
  }

  function handlerAttrChoose(attr) {
    console.log(attr, selectedAttr)
    if (attr.goods_sku_attr_id === selectedAttr[attr.goods_attr_id].key) {
      console.log('点击相同的sku了');
    } else {
      // 查找库存
      let temp = { ...selectedAttr };
      temp[attr.goods_attr_id] = {
        key: attr.goods_sku_attr_id,
        value: attr.attr_name
      };
      checkStorage(temp)
      setPurcharseNum(1)
    }
  }

  function purchase() {
    if (!Taro.getStorageSync('token') && !Taro.getStorageSync('userInfo')) {
      Taro.navigateTo({
        url: `/subPackageWork/pages/login/index`
      })
    } else {
      if (checkedSku.storage <= 0) {
      } else {
        purchaseGood({
          sku_id: checkedSku.skuId,
          num: purcharseNum,
          exchange_no: code,
          card_no: Taro.getStorageSync('card_no'),
          electronic_card_id: electronicCardId,
        }).then(res => {
          // console.log(res)
          if (goodsType === 0) {
            Taro.setStorageSync('deliveryTime', deliveryTime);
          }
          Taro.navigateTo({
            url: `/subPackageWork/pages/settlement/index?code=${code}`
          })
        })
      }
    }
  }

  function close() {
    if (!exchangeData) {
      props.onClose();
    }
  }

  function opt(type) {
    // 1 add 0 min
    if (exchangeData) {
    } else {
      if (type) {
        if (purcharseNum < checkedSku.storage) {
          setPurcharseNum(purcharseNum + 1);
        }
      } else {
        if (purcharseNum > 1) {
          setPurcharseNum(purcharseNum - 1);
        }
      }
    }
  }

  function dateChange(e) {
    if (e.detail.value == '2021-02-11' || e.detail.value == '2021-02-12' || e.detail.value == '2021-02-13') {
      Taro.showToast({
        title: '春节期间不发货,请重新选择发货时间!',
        icon: 'none'
      });
    } else {
      let temp = e.detail.value.split('-');
      setDeliveryTime(`${temp[0]}年${temp[1]}月${temp[2]}日`);
    }
  }

  return (
    <View className="wrapper" style={`top: ${navigationBarHeight}; height: calc(100% - ${navigationBarHeight})`}>
      <View className="top">
        <Image mode="aspectFit	" src={fishImg} className="cover" />
      </View>
      <View className="middle">
        <View className="title">
          <View className="text">选择</View>
          <View className="close" onClick={close}>×</View>
        </View>
        {exchangeData ? <View className="card">
          选择卡券类型
          <View className="card-selected">“已选{findCardType.attr_name}”</View>
          <View className="card-value-wrapper">

            {exchangeData.card.has_attr[0].has_goods_sku_attr.map((value, index) => {
              return value.goods_sku_attr_id === findCardType.goods_sku_attr_id ? (
                <View
                  className={
                    value.goods_sku_attr_id === findCardType.goods_sku_attr_id
                      ? 'card-value active'
                      : 'card-value'
                  }
                  key={value.goods_attr_id}
                >
                  {value.attr_name}
                </View>
              ) : null;
            })}
          </View>
        </View> : ''}
        {
          (exchangeData ? exchangeData.goods.has_attr : goodsAttr).map(attr => {
            return <View className="attr" key={attr.goods_attr_id}>
              <View className="attr-name">
                {attr.attr_name}
                {selectedAttr[attr.goods_attr_id] &&
                  <View className="attr-selected">
                    已选”{selectedAttr[attr.goods_attr_id].value}“
                  </View>}
              </View>
              <View className="attr-value-wrapper">
                {
                  attr.has_goods_sku_attr.map((value, index) => {
                    return value.attr_cover ?
                      <Image
                        onClick={() => handlerAttrChoose(value)}
                        key={value.goods_attr_id}
                        className={selectedAttr[attr.goods_attr_id].key === value.goods_sku_attr_id ?
                          'attr-image-value active' : 'attr-image-value'}
                        src={fullImgUrl(value.attr_cover)} />
                      :
                      <View
                        className={selectedAttr[attr.goods_attr_id].key === value.goods_sku_attr_id ?
                          'attr-value active' : 'attr-value'}
                        key={value.goods_attr_id}
                        onClick={() => handlerAttrChoose(value)}
                      >
                        {value.attr_name}
                      </View>
                  })
                }
              </View>
            </View>
          })
        }
        {!electronicCardId &&
          <View className="storage">
            <View className="text">数量</View>
            <View className="number"></View>
            <View className="opt-wrapper">
              <View className="opt add" onClick={() => opt(0)}>-</View>
              <View className="opt">{exchangeData ? 1 : `${purcharseNum}`}</View>
              <View className="opt min" onClick={() => opt(1)}>+</View>
            </View>
          </View>
        }
        {/* } */}
        {goodsType === 0 && <Picker className="date-picker" value={deliveryTime} mode='date' start={startDeliveryTime} onChange={dateChange}>
          <View className="wrap">
            <View className="text">发货时间</View>
            <View className="number">{deliveryTime}</View>
          </View>
        </Picker>}
      </View>
      <View className="bottom">
        <View className="text">{exchangeData ? '兑换卡兑换' : `￥${parseFloat(purcharseNum * checkedSku.price).toFixed(2)}`}</View>
        <View className="btn" onClick={purchase}>{exchangeData ? '立即兑换' : '立即购买'}</View>
      </View>
    </View>
  )
}

export default Sku;
